package com.zjt.smart.ui.base;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.zjt.smart.R;
import com.zjt.smart.app.Config;
import com.zjt.smart.mvp.view.LoadView;
import com.zjt.smart.ui.adapter.base.BaseAdapter;

import java.util.List;

public abstract class PageFragment<DataType> extends ScrollFragment implements LoadView<DataType> {
    protected long mCacheTime = 0;
    protected LoadView<DataType> mLoadView;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mLoadView = createLoadView();
        if (canLoadCache()){
            onLoadPage(1, mLoadView, true);
        } else {
            onLoadPage(1, mLoadView, false);
        }
    }

    @Override
    protected int layoutId() {
        return R.layout.fragment_page;
    }

    @Override
    public void onRefreshDelayed() {
        super.onRefreshDelayed();
        onLoadPage(1, mLoadView, false);
    }

    @Override
    public void onLoadMore(int toToLoadPage) {
        onLoadPage(toToLoadPage, mLoadView, false);
    }

    @Override
    public void onErrorClick() {
        super.onErrorClick();
        onLoadPage(1, mLoadView, false);
    }

    @Nullable
    @Override
    public void onSuccess(List<DataType> data) {
        if (getAdapter() == null){
            return;
        }
        mCacheTime = System.currentTimeMillis();
        showContentView();
        getAdapter().addAll(data);
    }

    @Override
    public void onCache(long cacheTime, List<DataType> data) {
        if (getAdapter() == null) {
            return;
        }
        if (data != null) {
            if (getAdapter().getItemCount() == 0) {
                showCacheView();
                getAdapter().addAll(data);
            }
            if (cacheTime != 0 && System.currentTimeMillis() - cacheTime > Config.CACHE_EXPIRE_TIME) {
                startRefresh();
            }
        } else {
            onLoadPage(1, mLoadView, false);
        }
    }

    @Override
    public void onFail(int errorCode, String errorMsg) {
        if (getAdapter() == null){
            return;
        }
        showErrorView(errorCode);
    }

    protected LoadView<DataType> createLoadView(){return this;}

    @Override
    protected abstract BaseAdapter createAdapter();

    protected abstract void onLoadPage(int pageNum, LoadView view, boolean fromCache);

    protected boolean canLoadCache(){
        return true;
    }
}
